import axios from 'axios'
import { MessageBox, Message,Notification } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.error(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code !== 0) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error(error.response)
    if (error.response.status === 401  ) {
      removeToken();
      if(router.currentRoute.path!="/login"){
        if(document.getElementsByClassName("el-message-box").length === 0){
          MessageBox.confirm('认证失效,请重新登录', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
      } else {
        Notification({
          title: '登录失败',
          message: error.response.data.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      // to re-login
    } else if (error.response.status == 403) {
      router.push({path: '/401'})
    } else {
      Notification({
        title: '异常',
        message: error.response.data.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service

export function isSuccess(res){
  return res&&res.code=== 0;
}
